{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 请添加自己的实验代码，点击运行查看结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from selenium import webdriver\n",
    "from selenium.webdriver.common.by import By\n",
    "from selenium.webdriver.edge.service import Service\n",
    "from webdriver_manager.microsoft import EdgeChromiumDriverManager\n",
    "import pandas as pd\n",
    "import time\n",
    "import matplotlib.pyplot as plt\n",
    "from wordcloud import WordCloud\n",
    "\n",
    "try:\n",
    "    # 启动Selenium WebDriver\n",
    "    service = Service(EdgeChromiumDriverManager().install())\n",
    "    driver = webdriver.Edge(service=service)\n",
    "    driver.get(\"https://www.worldometers.info/world-population/population-by-country/\")\n",
    "\n",
    "    # 等待页面加载完成\n",
    "    time.sleep(5)  # 根据网速和电脑性能调整等待时间\n",
    "\n",
    "    # 获取页面中的表格数据\n",
    "    table = driver.find_element(By.CSS_SELECTOR, \"table.table\")\n",
    "\n",
    "    # 读取表格数据到DataFrame\n",
    "    df = pd.read_html(table.get_attribute('outerHTML'))[0]\n",
    "\n",
    "finally:\n",
    "    # 确保浏览器关闭\n",
    "    driver.quit()\n",
    "\n",
    "\n",
    "# 写入Excel文件\n",
    "excel_path = 'D:\\PopVizCrawler\\PopVizCrawler\\data.xlsx'\n",
    "with pd.ExcelWriter(excel_path, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:\n",
    "    df.to_excel(writer, sheet_name='A股数据', index=False)\n",
    "\n",
    "print(\"数据已写入Excel文件\")\n",
    "\n",
    "\n",
    "# 读取Excel文件\n",
    "excel_path = 'D:\\PopVizCrawler\\PopVizCrawler\\data.xlsx'\n",
    "df = pd.read_excel(excel_path, sheet_name='A股数据')\n",
    "\n",
    "# 准备数据\n",
    "top_countries = df.nlargest(10, 'Population  (2023)')  # 人口最多的10个国家\n",
    "pop_density = df[['Country (or dependency)', 'Density  (P/Km²)']].set_index('Country (or dependency)')\n",
    "pop_growth = df[['Country (or dependency)', 'Yearly  Change']].set_index('Country (or dependency)')\n",
    "world_share = df[['Country (or dependency)', 'World  Share']].set_index('Country (or dependency)')\n",
    "\n",
    "# 创建画布和子图\n",
    "fig, axes = plt.subplots(2, 2, figsize=(14, 10))\n",
    "fig.suptitle('World Population Data Visualization', fontsize=16)\n",
    "\n",
    "# 柱状图：人口最多的10个国家\n",
    "top_countries.plot(kind='bar', x='Country (or dependency)', y='Population  (2023)', ax=axes[0, 0], legend=False)\n",
    "axes[0, 0].set_title('Top 10 Countries by Population')\n",
    "axes[0, 0].set_ylabel('Population (2023)')\n",
    "\n",
    "# 折线图：人口密度\n",
    "pop_density.sort_values('Density  (P/Km²)', ascending=False).head(10).plot(kind='line', ax=axes[0, 1], legend=False, marker='o')\n",
    "axes[0, 1].set_title('Top 10 Countries by Population Density')\n",
    "axes[0, 1].set_ylabel('Density (P/Km²)')\n",
    "\n",
    "# 饼图：世界人口份额\n",
    "world_share['World  Share'] = world_share['World  Share'].str.rstrip('%').astype('float') / 100.0\n",
    "world_share.head(10).plot(kind='pie', y='World  Share', ax=axes[1, 0], autopct='%1.1f%%', legend=False)\n",
    "axes[1, 0].set_title('World Population Share of Top 10 Countries')\n",
    "axes[1, 0].set_ylabel('')\n",
    "\n",
    "# 词云：国家名称\n",
    "wordcloud = WordCloud(width=400, height=400, background_color='white').generate(' '.join(df['Country (or dependency)']))\n",
    "axes[1, 1].imshow(wordcloud, interpolation='bilinear')\n",
    "axes[1, 1].set_title('Country Name Word Cloud')\n",
    "axes[1, 1].axis('off')\n",
    "\n",
    "# 调整子图间距\n",
    "plt.tight_layout(rect=[0, 0.03, 1, 0.95])\n",
    "\n",
    "# 显示图表\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
